#! /usr/bin/env python
# -*- coding: utf-8 -*-
import struct 

class DataConvert():

    def __init__(self):
        pass

    def InsertBlock(self,hex_str): 
        '''
            输入： test_data = "123456789012345"
            输出： 12 34 56 78 90 12 34 50
        '''
        if type(hex_str) != type("12"):
            print("hex_str is not 'str' type!")
            return None
        else:
            if len(hex_str)%2 != 0:
                hex_str += '0'
                print("add '0' at end,amended: ",end="")
                print(hex_str)
            hex_str_len = len(hex_str)
            # print(hex_str_len)
            hex_str_list = ["".join(hex_str[2*i:2*i+2]) for i in range(hex_str_len//2)]
            # print(hex_str_list)
            return " ".join(hex_str_list)

    def ToHexStr(self,data):
        '''
            输入： test_data = [1,2,3,4,5,6,7,]
            输出： 01020304050607

            输入： test_data = b'\x01\x02\x03\x04\x05\x06\x07'
            输出： 01020304050607        
        '''
        if type(data) == type([1,]):
            bytes_data = self.ToBytes(data)
            return bytes_data.hex()
        elif type(data) == type(b'\x00'):
            return data.hex()    
        else:
            print("only 'list' or 'bytes' is valid!")
            return None    

    def ToIntList(self,data):
        '''
            输入： 010203040506071  
            自动补为 0102030405060710
            输出： [1, 2, 3, 4, 5, 6, 7, 16]

            输入： b'\x01\x02\x03\x04\x05\x06\x07'
            输出： [1, 2, 3, 4, 5, 6, 7]        
        '''
        if type(data) == type('12'):
            bytes_data = self.ToBytes(data)
            return list(bytes_data) 
        elif type(data) == type(b'\x00'):
            return list(data)
        else:
            print("only 'str' or 'bytes' is valid!")
            return None   
            
    def ToBytes(self,data):
        '''
            输入： 010203040506071  
            输出： b'\x01\x02\x03\x04\x05\x06\x07\x10'

            输入： [1, 2, 3, 4, 5, 6, 7]
            输出： b'\x01\x02\x03\x04\x05\x06\x07'        
        '''    
        if type(data) == type('12'):
            if len(data)%2 != 0:
                data += '0'
                print("add '0' at end,amended: ",end="")
                print(data)
            return bytes().fromhex(data)
        elif type(data) == type([1,]):
            return bytes(data)
        else:
            print("only 'str' or 'list' is valid!")
            return None   

    def hex2ascii(self,data):
        '''
        输入： string ='7061756c'
        输出 ：string = 'paul'
        '''
        return(bytearray.fromhex(data).decode())

    def ascii2hex(self,data):
        '''
        输入 ：str='paul'
        输出 ： string ='7061756c'
        '''
        hexstr = ""
        databytes = bytes(data, "UTF-8")
        for i in range(len(data)):
            hexstr += ("%02x" % databytes[i]) + " "
        return hexstr.upper()

    def hex2float(self,data,convertType="floatABCD"):
        '''
        输入  test =  'F4CEF042'
        输出  120.4042053222656
        f 代表1个fudian
        <  代表读取模式  小端 ABCD
        >  代表读取模式  大端 DCBA
        '''
        #return(struct.unpack('<f', bytes.fromhex(data))[0])
        #print (data)
        if convertType == "floatABCD":
            #print( bytes.fromhex(data) )
            return(struct.unpack('<f', bytes().fromhex(data))[0])
        elif convertType == "floatDCBA":
            return(struct.unpack('>f', bytes().fromhex(data))[0])
        else:
            pass

    def hex_chunk_into_float(self,data):
        '''
        将整串的字符串：'132E5001'

        转换成两个为一个浮点型数据

        但是注意，只有像这样八个一组格式的才能转换

        而且这个方程，你的输入可以是一个string，也可以是一个string的列表，它还给你的也是相应的格式
        '''
        #fit_blocks = data
        floats=[struct.unpack('!f', bytes.fromhex(block))[0] for block in data] 

        return floats

    @staticmethod
    def hex2int(self, data):
        """
        docstring
        """
        return int( data, 16 )

if __name__ == "__main__":

    
    dc = DataConvert()

    x ='3a3031303331343432383233333333343144333333333334314343434343443431444536363636343236313939394144440d0a'
    print( dc.hex2ascii(x) )
    s = ":01030000000AF2"
    print(bytes(s,encoding='utf8')+b'\r\n')

    c= "0005"
    d= "0x"+c

    print (int(d,16))

    print( struct.unpack('>h', bytes().fromhex("0005"))[0] )



    # test =  'cd4c6e43'  #238.3

    # test2 = '00004000'  # 2.0

    # print("----------------")
    # print (type(test))

    # print( dc.hex2float(test) )
    # test =  '7061756c'

    # print(Data_Convert(test_data).hex2ascii())
    
    # print("MyConvert module test code:------------------",end="\n\n")
    
    test_data = "123456789012345"
    # print("input : ",end="")
    # print(test_data)
    # print("output: ")
    #print(Data_Convert(test_data).InsertBlock(),end="\n\n")
    
    # test_data = [1,2,3,4,5,6,7,]
    # print("input : ",end="")
    # print(test_data)
    # print("output: ")
    # print(ToHexStr(test_data),end="\n\n---")
    
    # test_data = [1,2,3,4,5,6,7,]
    # print("input : ",end="")
    # print(test_data)
    # print("output: ")
    # test_data = b'\x01\x02\x03\x04\x05\x06\x07'
    # print(ToHexStr(test_data),end="\n\n---------")
    
    # test_data = "010203040506071"
    # print("input : ",end="")
    # print(test_data)
    # print("output: ")
    # print(ToBytes(test_data),end="\n\n---------------------------")
    
    # test_data = [1,2,3,4,5,6,7,]
    # print("input : ",end="")
    # print(test_data)
    # print("output: ",end="")
    # print(ToBytes(test_data),end="\n\n")
    
    # test_data = "010203040506071"
    # print("input : ",end="")
    # print(test_data)
    # print("output: ")
    # print(ToIntList(test_data),end="\n\n")
    
    # test_data = b'\x01\x02\x03\x04\x05\x06\x07'
    # print("input : ",end="")
    # print(test_data)
    # print("output: ")
    # print(ToIntList(test_data),end="\n\n")
